//DeepSeek API 使用与 OpenAI 兼容的 API 格式，通过修改配置，您可以使用 OpenAI SDK 来访问 DeepSeek API，或使用与 OpenAI API 兼容的软件。
import OpenAI from "openai";
import fileutils from '../../js/fileutil'

let initMessages = [{ role: "system", content: "你是一个文档内容优化助手，现在有一段内容需要你进行润色优化，润色后直接返回最终内容，不需要多余的优化的解释说明" }]
let messages = initMessages


let modelName = "deepseek-reasoner"
let baseURL = "https://api.deepseek.com/v1"
let apiKey = "sk-5e9b169a9b1e4c17bbe43feedf5a4dd5"
loadBaseConfig()
let deepseek = new OpenAI({
  baseURL: baseURL,
  apiKey: apiKey,
  dangerouslyAllowBrowser: true
});

function loadBaseConfig() {
  baseURL = fileutils.getItem(fileutils.LLM_BASE_URL_KEY)
  apiKey = fileutils.getItem(fileutils.LLM_APIKEY_KEY)
  modelName = fileutils.getItem(fileutils.LLM_MODEL_NAME)
}



async function reqText(messages, callbackFunction) {
  console.log(messages)
  const completion = await deepseek.chat.completions.create({
    messages: messages,
    model: modelName,
    stream: true
  });
  let fullSingleMsg = ''
  for await (const chunk of completion) {
    let tempConetnet = chunk.choices[0]?.delta?.content || ''
    callbackFunction(tempConetnet)
    fullSingleMsg += tempConetnet
  }
  let amsg = { role: "assitant", content: fullSingleMsg.split("</think>")[1] }
  messages.push(amsg)
  console.log(fullSingleMsg.split("</think>")[1])
  //todo此处需要补全写入到wps
  //callbackFunction(respMsg.content)
}

function clearMsg() {
  messages = []
  alert("记忆重置成功")
}

function chatText(prompt, selectionContent, callbackFunction) {
  loadBaseConfig()
  console.log(messages)
  //记忆重置有问题，暂时去除记忆功能
  messages = []
  messages[0] = { role: "system", content: prompt }
  let message = { role: "user", content: selectionContent }
  messages.push(message)
  reqText(messages, callbackFunction)
}

export default {
  clearMsg,
  chatText,
  loadBaseConfig
}
